<!-- 用户添加 -->
<template>
  <div class="user-add">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">用户管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>添加用户</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="user-content">
      <el-card class="box-card">
        <!-- :rules="rules" 绑定验证规则 -->
        <el-form
          :model="addData"
          ref="ruleForm"
          label-width="70px"
          :rules="rules"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addData.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addData.password" show-password></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="addData.phone"></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="addData.sex">
              <el-radio label="保密"></el-radio>
              <el-radio label="男"></el-radio>
              <el-radio label="女"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="等级" prop="level">
            <el-radio-group v-model="addData.level">
              <el-radio label="1">管理员</el-radio>
              <el-radio label="2">普通用户</el-radio>
              <el-radio label="3">会员</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="年龄" prop="age">
            <el-input v-model.number="addData.age"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addData.email"></el-input>
          </el-form-item>
          <el-form-item label="头像">
            <el-upload
              class="avatar-uploader"
              :action="Setting.apiBaseUrl + '/upload/img'"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="imageUrl"
                :src="Setting.baseUrl + imageUrl"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="地址" prop="address">
            <el-input v-model="addData.address" type="textarea"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')"
              >添加用户</el-button
            >
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import validateReg from "@/utils/validateReg.js";
import Setting from "@/utils/setting.js";
// 按需引入api
import { userAddApi } from "@/api/user.js";
console.log(validateReg);
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    // 密码
    var validatePass = (rule, value, callback) => {
      console.log(rule);
      console.log(value);
      console.log(callback);
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        callback();
      }
    };
    // 年龄
    var checkAge = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("年龄不能为空"));
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error("请输入数字值"));
        } else {
          if (value < 18) {
            callback(new Error("必须年满18岁"));
          } else {
            callback();
          }
        }
      }, 1000);
    };
    // 手机号;
    var checkPhone = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else {
        if (!validateReg.regPhone.test(value)) {
          callback(new Error("请输入正确的手机格式"));
        }
        callback();
      }
    };
    // 邮箱
    var checkEmail = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入邮箱"));
      } else {
        if (!validateReg.regEmail.test(value)) {
          callback(new Error("请输入正确的邮箱格式"));
        }
        callback();
      }
    };
    return {
      addData: {
        username: "",
        password: "",
        phone: "",
        sex: "保密",
        level: "2",
        age: "",
        email: "",
        address: "",
      },
      imageUrl: "",
      rules: {
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            validator: validatePass,
          },
        ],
        age: [
          {
            validator: checkAge,
          },
        ],
        phone: [
          {
            required: true,
            validator: checkPhone,
          },
        ],
        email: [
          {
            validator: checkEmail,
          },
        ],
      },
      // 设置服务器地址等
      Setting: Setting,
    };
  },
  //计算属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    // 头像图片上传成功的处理
    handleAvatarSuccess(res, file) {
      console.log(res);
      console.log(file);
      this.imageUrl = res.data.name;
      // this.imageUrl = URL.createObjectURL(file.raw);
    },
    // 头像上传之前的验证
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 提交表单的验证
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // alert("submit!");
          this.addData.imgsrc = this.imageUrl;
          // this.$set(this.addData, "imgsrc", this.imageUrl);
          // console.log(this.addData);
          // 对数据进行处理
          // 发送axios请求请求数据
          userAddApi(this.addData).then((res) => {
            if (res.data.status == 200) {
              console.log(res.data);
              this.$router.push("/admin/user/list");
            } else {
              alert(res.data.msg);
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 重置的设置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
  beforeCreate() {}, //生命周期 - 创建之前
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  beforeMount() {}, //生命周期 - 挂载之前
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang="less">
.user-add {
  .user-content {
    height: 550px;
    overflow: auto;
    .box-card {
      height: 1000px;
      .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
      }
      .avatar-uploader .el-upload:hover {
        border-color: #409eff;
      }
      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 60px;
        height: 60px;
        line-height: 60px;
        text-align: center;
      }
      .avatar {
        width: 60px;
        height: 60px;
        display: block;
      }
      .el-textarea__inner {
        resize: none;
      }
    }
  }
}
</style>